<template>
  <div class="cil-tabs">
    <div class="cil-tabs-nav" ref="container">
      <div class="cil-tabs-nav-item"
        v-for="(item, idx) in items" :key="idx"
        :class="{selected: item.props.title === selected}"
        @click="select(item)"
        :ref="el => { if(item.props.title === selected) selectedItem = el }">
        {{item.props.title}}
      </div>
      <div ref="indicator" class="cil-tabs-nav-indicator"></div>
    </div>
    <div class="cil-tabs-content">
      <component class="cil-tabs-content-item"
        :is="current" :key="current.props.title" />
    </div>
  </div>
</template>

<script lang="ts">
import { computed, onMounted, ref, watchEffect } from 'vue'
import Tab from './Tab.vue'

export default {
  props: {
    selected: {
      type: String,
    }
  },
  setup(props, ctx) {
    const selectedItem = ref<HTMLDivElement>()
    const indicator = ref<HTMLDivElement>(null)
    const container = ref<HTMLDivElement>(null)
    
    onMounted(() => {
      watchEffect(
        () => {
          const { width } = selectedItem.value.getBoundingClientRect()
          indicator.value.style.width = width + 'px'
          const { left: containerLeft } = container.value.getBoundingClientRect()
          const { left: itemLeft } = selectedItem.value.getBoundingClientRect()
          const left = itemLeft - containerLeft
          indicator.value.style.left = left + 'px'
        },
        {
          flush: 'post',
        }
      )
    })
    
    const items = ctx.slots.default()
    items.forEach((item) => {
      // @ts-ignore
      if (item.type.name !== Tab.name) {
        throw new Error(`Tabs' children should be Tab`)
      }
    })
    const current = computed(() => {
      return items.filter(item => item.props.title === props.selected)[0]
    })
    const select = (item) => {
      ctx.emit('update:selected', item.props.title)
    }
    return {
      selectedItem,
      indicator,
      container,
      items,
      current,
      select,
    }
  }
}
</script>

<style lang="scss">
$blue: #40a9ff;
$color: #333;
$border-color: #d9d9d9;

.cil-tabs {
  &-nav {
    display: flex;
    color: $color;
    border-bottom: 1px solid $border-color;
    position: relative;

    &-item {
      padding: 8px 0;
      margin: 0 16px;
      cursor: pointer;

      &:first-child {
        margin-left: 0;
      }

      &.selected {
        color: $blue;
      }
    }
    &-indicator {
      position: absolute;
      height: 3px;
      background: $blue;
      left: 0;
      bottom: -1px;
      width: 100px;
      transition: all 250ms;
    }
  }

  &-content {
    padding: 8px 0;
  }
}
</style>